package com.hunhjy.core.handler;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import com.hunhjy.core.kit.StrKit;

/**
 * mybatis string类型转Date类型(yyyy-MM-dd HH:mm:ss)处理类.
 * 
 * @author Dawn
 * @version 1.0
 */
@MappedJdbcTypes(JdbcType.VARCHAR)
public class StringToDateHandler extends BaseTypeHandler<Date> {
	private static final Logger LOG = LogManager.getLogger(StringToDateHandler.class);
	private static final DateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

	@Override
	public void setNonNullParameter(PreparedStatement ps, int i, Date parameter, JdbcType jdbcType)
			throws SQLException {
		ps.setString(i, DATE_FORMAT.format(parameter));
	}

	@Override
	public Date getNullableResult(ResultSet rs, String columnName) throws SQLException {
		String sqlTimestamp = rs.getString(columnName);

		if (!StrKit.isBlank(sqlTimestamp)) {
			try {
				return DATE_FORMAT.parse(sqlTimestamp);
			} catch (ParseException e) {
				LOG.error("日期转换错误", e);
			}
		}
		return null;
	}

	@Override
	public Date getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
		String sqlTimestamp = rs.getString(columnIndex);
		if (!StrKit.isBlank(sqlTimestamp)) {
			try {
				return DATE_FORMAT.parse(sqlTimestamp);
			} catch (ParseException e) {
				LOG.error("日期转换错误", e);
			}
		}
		return null;
	}

	@Override
	public Date getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
		String sqlTimestamp = cs.getString(columnIndex);
		if (!StrKit.isBlank(sqlTimestamp)) {
			try {
				return DATE_FORMAT.parse(sqlTimestamp);
			} catch (ParseException e) {
				LOG.error("日期转换错误", e);
			}
		}
		return null;
	}
}
